import api from "../../config/api"
import request from "../../utils/request"
import { getUserCamera, getUserPermissions, setUserCamera, shareOptions } from "../../utils/access"
import { getBarAndTitleHeight, getStorage, getXsScreen, goBack, isMiniPhone, jump, stringify } from "../../utils/utils"
import { uploadAliyun } from "../../utils/UploadAliyun"
import { formatTime, paramSplicing } from "../../utils/utils"
import report from "../../utils/report"

const app = getApp()

// pages/categoryPhoto/categoryPhoto.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 顶部背景高度
    bgTopHeight: 0,
    // 中间背景高度
    bgCenterHeight: 0,
    // 底部背景高度
    bgBottomHeight: 0,
    // 是否是垃圾桶内
    isBucket: true,
    // 是否是圆形框
    isCircle: true,
    // 框类型集合
    frameScreenMap: {
      normal: {
        // 厨余圆形框
        kitchenCircle: 'https://image-classify.daieco.com/kejian-quanzi/d1FiNK7IinvU0c58b728a72b83904d587314b0c1a8ac.png',
        // 厨余方形框
        kitchenSquare: 'https://image-classify.daieco.com/kejian-quanzi/1dhUAjqTl2Qm69b30a630f0cdfb7e53b26fa7b8014f0.png',
        // 其他圆形框
        otherCircle: 'https://image-classify.daieco.com/kejian-quanzi/sbUqxCSrwhkY35d1094986c980f99014ab37ae58f37e.png',
        // 其他方形框
        otherSquare: 'https://image-classify.daieco.com/kejian-quanzi/TPGxlM0SismW8d8460b3962774b7d210898ad29c51d8.png',
        // 普通圆形框
        normalCircle: 'https://image-classify.daieco.com/kejian-quanzi/WAbriTXpU5Hv8f9d105ab37b6fb5ecd8092a134ce5ac.png',
        // 普通方形框
        normalSquare: 'https://image-classify.daieco.com/kejian-quanzi/HOd2ABV9Yd348dc502121bc8062ac87020c9c50bc224.png',
      },
      xs: {
         // 厨余圆形框
        kitchenCircle: 'https://image-classify.daieco.com/kejian-quanzi/OK7K9F46D9dcd0ad41d53ca5b773dca59a2617e6e6ac.png',
        // 厨余方形框
        kitchenSquare: 'https://image-classify.daieco.com/kejian-quanzi/WCpYbyBTRIhDc6b811a626f735158d608d3b7274ab67.png',
        // 其他圆形框
        otherCircle: 'https://image-classify.daieco.com/kejian-quanzi/7wy2K48ddU1kef145077eff08a06dcf0824c4aa4ba19.png',
        // 其他方形框
        otherSquare: 'https://image-classify.daieco.com/kejian-quanzi/GwxxGgIQNzL9b1440629c2f27da60a18539a7b17e693.png',
        // 普通圆形框
        normalCircle: 'https://image-classify.daieco.com/kejian-quanzi/VC44DzTkwylg80feecd7ceabf6c195a7c972b3884446.png',
        // 普通方形框
        normalSquare: 'https://image-classify.daieco.com/kejian-quanzi/e1aiikFuDQZlff8e9d7d360861abd3dfee2588ffa0c7.png',
      },
    },
    // 框类型集合
    frameMap: {},
    // 桶背景图
    bucketImage: null,
    // 垃圾类型 1: 厨余, 2: 其他
    putTaskType: null,
    // 来源 1签到页 2首页底部/拍照 3挑战 
    source: 2,
    // 分类签到天数
    signDays: 0,
    // 显示分类签到天数
    showDays: false,
    // 投放任务ID
    taskId: null,
    // 投放任务标题
    taskTitle: null,
    // 投放任务类型
    taskType: null,
    // 挑战的第几天
    challengeDay: null,
    // 拍照图片
    photo: null,
    // 图片原始宽度
    imageWidth: 0,
    // 图片原始高度
    imageHeight: 0,
    // 隐藏相机
    cameraHide: false,
    // 场景初始滑动位置
    sceneScrollX: 0,
    // 是否是红米K30S
    isRedmiK30S: false,
    // 信号栏高度
    ...getBarAndTitleHeight(),
    // 是否是小屏幕尺寸
    ...getXsScreen(),
    // 屏幕宽度
    winWidth: 0,
    // 屏幕高度
    winHeight: 0,
    // 拍照区域顶部距离
    totalTop: 0
  },
  
  // 相机实例
  ctx: null,
  // 请求loading
  loading: false,

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.options = options
    console.log('分类拍照页面参数', options)

    const { isXsScreen, frameScreenMap } = this.data
    this.setData({
      frameMap: frameScreenMap[isXsScreen ? 'xs' : 'normal']
    })

    setTimeout(() => {
      const systemInfo = wx.getSystemInfoSync()
      // 顶部背景高度
      let bgTopHeight = Number((systemInfo.windowHeight * (isXsScreen ? 0.01 : (isMiniPhone() ? 0.05 : 0.107))).toFixed(0))
      const topLastNum = Number((bgTopHeight.toString().split('').pop()))

      console.log('------------',topLastNum)
      if (topLastNum < 2) {
        bgTopHeight = bgTopHeight - topLastNum
      } else {
        bgTopHeight = bgTopHeight + 10 - topLastNum
      }
      // 中间背景高度
      let bgCenterHeight = systemInfo.windowWidth
      const centerLastNum = Number((bgCenterHeight.toString().split('').pop()))
      if (centerLastNum < 2) {
        bgCenterHeight = bgCenterHeight - centerLastNum
      } else {
        bgCenterHeight = bgCenterHeight + 10 - centerLastNum
      }

      const { isCircle } = this.data
      const putTaskType = +options.putTaskType || ''

      this.setData({
        bgTopHeight,
        bgCenterHeight,
        bgBottomHeight: systemInfo.windowHeight - bgCenterHeight - bgTopHeight,
        isBucket: !(+options?.isAny),
        putTaskType,
        source: +options?.source || 2,
        isRedmiK30S: systemInfo.brand === 'Redmi' && systemInfo.model === 'M2007J3SC',
        signDays: options.signDays,
        taskId: options.taskId,
        taskTitle: options.title,
        taskType: options.taskType,
        challengeDay: options.challengeDay,
        bucketImage: this.getBucketImage(putTaskType, isCircle),
        winWidth: systemInfo.windowWidth,
        winHeight: systemInfo.windowHeight
      })
      this.ctx = wx.createCameraContext()
    }, 300)
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    setTimeout(() => {
      if (this.data.source === 1 || app.isLogin()) {
        this.getUserData()
      }

      // 获取拍照区域距离顶部多少
      this.getTotalTop()
    }, 400)
  },
  // 获取桶背景图片
  getBucketImage(putTaskType, isCircle) {
    const { frameMap } = this.data
    return putTaskType ? (isCircle
      ? (putTaskType === 1 ? frameMap.kitchenCircle : frameMap.otherCircle)
      : (putTaskType === 1 ? frameMap.kitchenSquare : frameMap.otherSquare))
      : (isCircle ? frameMap.normalCircle : frameMap.normalSquare)
  },
  // 清除图片信息
  clearPhotoInfo() {
    this.loading = false
    wx.hideLoading()
    this.setData({
      photo: null,
    })
  },
  // 框形态切换
  frameSwitch(e) {
    if (this.loading) return
    const isCircle = e?.currentTarget?.dataset?.type === 'circle'
    const { putTaskType } = this.data
    this.setData({
      isCircle,
      bucketImage: this.getBucketImage(putTaskType, isCircle),
    })
  },
  // 场景切换
  sceneSwitch(e) {
    if (this.loading) return
    this.setData({
      isBucket: e?.currentTarget?.dataset?.type === 'bucket'
    })

    if(e?.currentTarget?.dataset?.type === 'bucket'){
      this.getTotalTop()
    }
  },
  // 获取拍照框距离顶部距离
  getTotalTop(){
    wx.createSelectorQuery().in(this).select('.page-bucket').boundingClientRect((res) => {
      this.setData({
        totalTop: res?.top,
      })
    }).exec()
  },
  // 相机权限通过
  cameraAuthPass(e) {
    console.log('相机加载完成', e)
    setUserCamera()
  },
  // 相机加载报错
  cameraAuthError(e) {
    console.log('相机加载报错', e)
    if (/auth (deny|denied|cancel|canceled)$/.test(e?.detail?.errMsg)) {
      return
    }
    wx.redirectTo({
      url: '/pages/categoryPhoto/categoryPhoto' + paramSplicing('', this.options),
    })
  },
  // 上报日志
  reportLog(originInfo, cropInfo) {
    console.log('上报信息：', originInfo, cropInfo)
    report.reportParams({
      data: {
        url: 'category-photo',
        appName: "operational-tools",
        level: 1001,
        message: JSON.stringify({
          originInfo,
          cropInfo
        }),
        param: 'category-photo',
        token: getStorage('token'),
        requestMethod: 'post',
      },
    })
  },
  // 点击拍照
  async takePhoto() {
    let that = this
    let { isBucket, bgCenterHeight, winWidth, winHeight, totalTop } = that.data
   
    // 测试代码
    // if (this.loading) return
    // this.loading = true
    // wx.showLoading({
    //   title: '识别中',
    // })
    // const res = {
    //   // tempImagePath: 'https://image-classify.daieco.com/kejian-photo/2021-12-06/tmp_257eca566eb5826cb6a89128d16f9fc78c5983febacebfcb.jpg',
    //   // tempImagePath: 'https://image-classify.daieco.com/kejian-photo/2022-03-10/tmp_f4788994c25fc7e1e8121795ffa5411e.png',
    //   tempImagePath: 'https://image-classify.daieco.com/kejian-photo/2022-03-10/tmp_e8626e694292d06960bdce623c14085d.png'
    // //   tempImagePath: 'https://image-classify.daieco.com/kejian-quanzi/J56ZnbgvBrWJe66068ac6a3a61471c6d8aa5ef5c47c1.jpg'
    // }
    // this.setData({
    //   photo: res.tempImagePath,
    // })
    // // 获取图片信息
    // wx.getImageInfo({
    //   src: res.tempImagePath,
    //   success: (imageRes) => {
    //     console.log('获取图片信息', imageRes)
    //     this.setData({
    //       imageWidth: imageRes.width,
    //       imageHeight: imageRes.height,
    //     })
    //     this.aiRequest(res.tempImagePath)
    //   },
    //   error: () => {
    //     this.clearPhotoInfo()
    //   },
    // })
    // return
    if (!getUserCamera()) {
      getUserPermissions('camera', (success) => {
        if (success) {
          this.ctx = null
          this.setData({
            cameraHide: true
          })
          setTimeout(() => {
            this.setData({
              cameraHide: false
            }, () => {
              this.ctx = wx.createCameraContext()
            })
          }, 200)
        }
      })
      return
    }
    if (this.loading) return
    this.loading = true
    const taskId = this.data.taskId
    if (taskId) {
      const res = await request.get(api.taskStatus, { userDayTaskId: taskId }, { loading: false })
      console.log('任务状态', res);
      if (res?.data === 1) {
        wx.showToast({
          icon: 'none',
          title: '该任务已经完成',
          duration: 2000
        })
        setTimeout(() => {
          wx.navigateBack({
            delta: 1,
          })
          this.loading = false
        }, 2000)
        return
      }
    }
    wx.showLoading({
      title: '识别中',
    })
    // 获取拍照图片
    this.ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        let photoPath = res.tempImagePath


      // wx.chooseImage({
      //   success (res) {
      //     console.log('res-------',res)
      //     let photoPath = res.tempFilePaths[0]
          
        that.setData({
          photo: photoPath,
        })

        // 桶内拍
        if(isBucket){
            console.log('原始图片信息：', res)
            
            // 矩形的位置
            var image_x = 0;
            var image_y = totalTop;
            var image_width = winWidth;
            var image_height = winWidth // bgCenterHeight;

            const canvas = wx.createCanvasContext('image-canvas', that)
            that.canvas = canvas
            that.canvas.drawImage(photoPath, 0, 0, winWidth,winHeight)
            that.canvas.draw()
            
            setTimeout(()=> {
              if (!that.canvas) {
                console.error('Canvas is undefined.')
                return
              }
              wx.canvasToTempFilePath({ //裁剪对参数
                // canvas: that.canvas,
                canvasId: "image-canvas",
                x: image_x, //画布x轴起点
                y: image_y, //画布y轴起点
                width: image_width, //画布宽度
                height: image_height, //画布高度
                destWidth: image_width, //输出图片宽度
                destHeight: image_height, //输出图片高度
                success: function(response) {
                  const fileManager = wx.getFileSystemManager()
                  fileManager.getFileInfo({
                    filePath: response.tempFilePath,
                    success: (sizeRes) => {
                      console.log('裁切图片数据：', response)
                      console.log('图片大小数据：', sizeRes)
                      if (sizeRes?.size) {
                        that.uploadImg(response.tempFilePath)
                      } else {
                        // 原始图片信息
                        let originInfo = {
                          ...res,
                        }
                        // 裁切图片信息
                        let cropInfo = {
                          ...response,
                          ...sizeRes,
                        }
                        fileManager.getFileInfo({
                          filePath: res.tempImagePath,
                          success: (originSizeRes) => {
                            console.log('原始图片大小数据：', originSizeRes)
                            originInfo = {
                              ...originInfo,
                              ...originSizeRes
                            }
                            uploadAliyun(res.tempImagePath, (originPhoto) => {
                              if (originPhoto) {
                                originInfo = {
                                  ...originInfo,
                                  url: originPhoto
                                }
                                uploadAliyun(response.tempFilePath, (cropPhoto) => {
                                  if (cropPhoto) {
                                    cropInfo = {
                                      ...cropInfo,
                                      url: cropPhoto
                                    }
                                    that.reportLog(originInfo, cropInfo)
                                  } else {
                                    that.reportLog(originInfo, cropInfo)
                                  }
                                }, { directory: `kejian-photo/${formatTime(new Date(), '-', false)}/` })
                              } else {
                                that.reportLog(originInfo, cropInfo)
                              }
                            }, { directory: `kejian-photo/${formatTime(new Date(), '-', false)}/` })
                          },
                          fail: () => {
                            that.reportLog(originInfo, cropInfo)
                          }
                        })
                        that.clearPhotoInfo()
                        wx.showToast({
                          title: '出错啦....',
                          icon: 'loading'
                        })
                      }
                    },
                    fail: () => {
                      that.clearPhotoInfo()
                      wx.showToast({
                        title: '出错啦.....',
                        icon: 'loading'
                      })
                    }
                  })
                },
                fail: function(e) {
                  that.clearPhotoInfo()
                  wx.showToast({
                    title: '出错啦...',
                    icon: 'loading'
                  })
                }
              },this);
            }, 1000);
        
        }else{
          // 任意拍
          that.uploadImg(photoPath)
        }
      },
      error: () => {
        this.clearPhotoInfo()
      },
    })
  },
  // 获取图片地址去请求接口
  uploadImg(filePath){
    wx.getImageInfo({
      src: filePath,
      success: (imageRes) => {
        console.log('获取图片信息', imageRes)
        this.setData({
          imageWidth: imageRes.width,
          imageHeight: imageRes.height,
        })
        // 上传阿里云
        uploadAliyun(filePath, (photo) => {
          if (photo) {
            // 调取ai接口
            this.aiRequest(photo)
          } else {
            this.clearPhotoInfo()
          }
        }, { directory: `kejian-photo/${formatTime(new Date(), '-', false)}/` })
      },
      error: () => {
        this.clearPhotoInfo()
      },
    })
  },
  // 调取ai接口
  async aiRequest(url) {
    console.log('页面所有数据', this.data)
    const {
      isBucket,
      challengeDay,
      taskId,
      putTaskType,
      source,
      signDays,
      taskTitle,
      imageWidth,
      imageHeight,
      showDays,
    } = this.data
    
    // 系统信息
    const systemInfo = wx.getSystemInfoSync()
    // px转换到rpx的比例
    const pxToRpxScale = 750 / systemInfo.windowWidth
    // 请求参数
    const params = {
      url,
      putTaskType,
      source,
      sceneType: isBucket ? 1 : 2,
      ...(isBucket ? { taskId } : {}),
      type: (isBucket && taskId) ? 1 : 2,
    }
    console.log('ai接口参数', params)
    const res = await request.post(
      app.isLogin() ? api.wechatPic : api.noLoginPic,
      params,
      { loading: false }
    )

    console.log('ai接口数据', res)
    const { name, type, garbageInnerVO, resultList, centralPoint, flag, signInStatus, showSignInRedPacket, signInId, ifTarget } = res?.data || {}
    if (source === 1 && signInStatus === 2) {
      wx.showToast({
        title: '今日签到已完成',
        icon: 'none',
        duration: 2000
      })
      setTimeout(() => {
        goBack(1, {
          complete: () => {
            this.clearPhotoInfo()
          }
        })
      }, 2000)
      return
    }
    
    wx.hideLoading()

    // 垃圾桶类型
    const bucketType = type === 1 ? [null, 'KitchenWaste', 'OtherWaste', 'MixedWaste', 'EmptyWaste']
      .indexOf(name || null) : 0
    // 第一件物品
    const [goodsName, goodsType] = ({ ...resultList?.[0] }.name || '').split(',')
    const [pointX, pointY] = (centralPoint || '0,0').split(',')
    // 桶内成分分析参数
    const analyzeParams = {
      // 拍照图片
      url,
      // 垃圾桶类型 0: 非垃圾桶 1: 厨余垃圾桶 2: 其他垃圾桶 3: 混合垃圾桶 4: 空垃圾桶
      bucketType,
      // 成分分析 garbageNameList: 桶内垃圾成分列表 garbageNum: 桶内成分数量
      ingredient: stringify({
        ...garbageInnerVO,
        garbageList: resultList?.map(item => ({
          name: item?.name?.split(',')?.[0],
          url: item.highLight
        }))
      }),
      // 签到ID
      signInId,
      // 是否有签到红包
      signInRedPacket: showSignInRedPacket ? true : '',
      // 任务ID
      taskId,
      // 识别物品名称
      goodsName,
      // 识别物品类型
      goodsType,
      // 桶中心点x坐标
      pointX: pointX === '0'
        ? (systemInfo.windowWidth / 2 * pxToRpxScale)
        : (+pointX * (systemInfo.windowWidth / imageWidth) * pxToRpxScale),
      // 桶中心点y坐标
      pointY: pointY === '0'
        ? (systemInfo.windowHeight / 2 * pxToRpxScale)
        : (+pointY * (systemInfo.windowHeight / imageHeight) * pxToRpxScale - (systemInfo.windowHeight / 2 * pxToRpxScale + 34) / 2),
      // 桶中心点y坐标2
      pointY2: pointY === '0'
        ? (systemInfo.windowHeight / 2 * pxToRpxScale)
        : (+pointY * (systemInfo.windowHeight / imageHeight) * pxToRpxScale - (systemInfo.windowHeight * pxToRpxScale - 378) / 2),
      // 桶中心点测试坐标
      pointZ: pointY === '0'
        ? (systemInfo.windowHeight / 2 * pxToRpxScale)
        : (+pointY * (systemInfo.windowHeight / imageHeight) * pxToRpxScale - 50),
    }

    if (res?.httpStatus === 200) {
      // 桶内拍
      if (isBucket) {
        // 跳转结果页或者桶内成分分析页
        jump(
          taskId
            ? (flag ? 'taskSucceed' : 'taskFail')
            : ((source === 1 || showDays) ? (signInStatus ? 'signSucceed' : 'signFail') : 'bucketAnalyse'),
          taskId ? {
            ...analyzeParams,
            // 任务标题
            taskTitle,
            // 任务类型 1: 厨余, 2: 其他
            putTaskType,
            // 挑战第几天
            challengeDay,
            // 任务是否成功
            success: +flag,
          } : {
            ...analyzeParams,
            signDays,
            ifTarget: ifTarget ? 1 : '',
            // showMsg
          },
          {
            complete: () => {
              this.clearPhotoInfo()
            }
          }
        )
      } else {
        // 任意拍
        // 计算日常拍点的位置 type: 1桶 2单品
        const result = (type === 1 ? [{ name, centralPoint: centralPoint || '0,0', type }] : resultList)?.map(item => {
          const point = item?.centralPoint?.split?.(',').map(Number)
          return {
            left: point?.[0],
            top: point?.[1],
            type: item.type,
            name: item.name,
            bgurl: url
          }
        }).filter(f => typeof f.left === 'number' && typeof f.top === 'number')
          .map(item => {
            const isEmpty = item.left === 0 && item.top === 0
            return {
              ...item,
              left: isEmpty
                ? (systemInfo.windowWidth / 2 - 35 * (systemInfo.windowWidth / 750))
                : (item.left * (systemInfo.windowWidth / imageWidth)),
              top: isEmpty
                ? (systemInfo.windowHeight / 2 - 35 * (systemInfo.windowWidth / 750))
                : (item.top * (systemInfo.windowHeight / imageHeight)),
            }
          })
        // 跳转多结果页面
        jump('clickMe', {
          result: stringify(result),
          ...analyzeParams,
          // showMsg
        }, {
          complete: () => {
            this.clearPhotoInfo()
          }
        })
      }
    } else {
      this.clearPhotoInfo()
    }
  },
  // 获取用户信息
  async getUserData(){
    const { source } = this.data
    const res = await request.get(api.userDays)

    this.setData({
      signDays: res?.data?.signInDays,
      showDays: Boolean(source === 2 && res?.data?.isNotSign)
    })
  },
  // 场景滑动开始
  sceneTouchStart(event) {
    this.setData({
      sceneScrollX: event?.touches?.[0]?.pageX || 0
    })
  },
  // 场景滑动移动
  sceneTouchMove(event) {
    const { sceneScrollX } = this.data
    const currentX = event?.touches?.[0]?.pageX || 0

    if (currentX <= sceneScrollX) {
      console.log('左滑')
      this.setData({
        isBucket: true
      })
    } else {
      console.log('右滑')
      this.setData({
        isBucket: false
      })
    }
  },
  // 用户点击右上角分享
  onShareAppMessage(e) {
    return shareOptions('default',e)
  },
})